package com.xgc.oauth.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * rsa工具类
 *
 * @author xgc
 * @date 2024/01/10
 */
@Slf4j
public class RsaUtil {
    public static Map<String, String> createKey() {
        Map<String, String> keyPairMap = new HashMap<>();
        KeyPairGenerator rsa = null;
        try {
            rsa = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage());
        }
        if (rsa != null) {
            rsa.initialize(1024, new SecureRandom());
            KeyPair keyPair = rsa.generateKeyPair();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥

            //获取公、私钥值
            String publicKeyValue = byte2Base64String(publicKey.getEncoded());
            String privateKeyValue = byte2Base64String(privateKey.getEncoded());

            keyPairMap.put("public", publicKeyValue);
            keyPairMap.put("private", privateKeyValue);
        }

        return keyPairMap;
    }

    public static RSAPrivateKey getPrivateKey(String privateKeyBase64Str) throws NoSuchAlgorithmException, InvalidKeySpecException {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(base64String2Byte(privateKeyBase64Str));
        KeyFactory keyFactory;
        keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    }

    public static RSAPublicKey getPublicKey(String publicKeyBase64Str) throws NoSuchAlgorithmException, InvalidKeySpecException {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(base64String2Byte(publicKeyBase64Str));
        KeyFactory keyFactory;
        keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }


    /**
     * base64字符串转字节数组
     *
     * @param base64Str
     * @return
     */
    public static byte[] base64String2Byte(String base64Str) {
        return Base64.getDecoder().decode(base64Str);
    }

    /**
     * 字节数组转base64字符串
     *
     * @param bytes
     * @return
     */
    public static String byte2Base64String(byte[] bytes) {
        return new String(Base64.getEncoder().encode(bytes));
    }

}
